package com.xxx.mysql.redpackage;

import java.math.BigDecimal;
import java.sql.*;

public class RedpackageManager extends Thread{

    public static final String URL = "jdbc:mysql://localhost:3306/redpackage";
    public static final String USER = "root";
    public static final String PASSWORD = "88888888";

    private String id1;
    private String id2;




    public RedpackageManager(String id, String id2) {
        this.id1 = id;
        this.id2 = id2;
    }

    public static Connection getConn() throws ClassNotFoundException, SQLException {

        Class.forName("com.mysql.cj.jdbc.Driver");

        Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);

        return connection;
    }

    public static void close(Connection conn, Statement statement, ResultSet rl) {

        try {
            if (rl != null) {
                rl.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (conn != null) {
                conn.close();
            }
        }catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    /**
     * 用户注册
     * @param ui
     */
    public static void login(UserInfo ui) {

        Connection conn = null;
        Statement statement = null;
        try {
            conn = RedpackageManager.getConn();

            statement = conn.createStatement();

            String sql = "insert into t_user_info (user_id , user_name , balance) values ( ? , ? , ? )";

            PreparedStatement ps = conn.prepareStatement(sql);

            ps.setString(1, ui.getUser_id());
            ps.setString(2, ui.getUser_name());
            ps.setBigDecimal(3, ui.getBalance());
            int i = ps.executeUpdate();

            if (i >= 1) {
                System.out.println("注册成功！");
                return;
            }
            System.out.println("注册失败！");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            RedpackageManager.close(conn , statement , null);
        }

    }

    /**
     * 修改用户信息
     * @param id2
     * @param ui
     */
    public static void updateUserInfo(String id2,UserInfo ui) {

        Connection conn = null;
        Statement statement = null;
        try {
            conn = RedpackageManager.getConn();
            statement = conn.createStatement();
            String sql = "UPDATE t_user_info SET user_id = ? , user_name = ? , balance = ? WHERE user_id = ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, ui.getUser_id());
            ps.setString(2, ui.getUser_name());
            ps.setBigDecimal(3, ui.getBalance());
            ps.setString(4, id2);
            int i = ps.executeUpdate();
            if (i >= 1) {
                System.out.println("修改成功！");
                return;
            }
            System.out.println("修改失败！");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            RedpackageManager.close(conn, statement, null);
        }

    }

    /**
     * 删除用户信息
     * @param id
     */
    public static void deleteUserInfo(String id ){

        Connection conn = null;
        Statement statement = null;
        try {
            conn = RedpackageManager.getConn();
            statement = conn.createStatement();
            String sql = "DELETE FROM t_user_info WHERE user_id = ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, id);
            int i = ps.executeUpdate();
            if (i >= 1) {
                System.out.println("删除成功！");
                return;
            }
            System.out.println("删除失败！");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            RedpackageManager.close(conn, statement, null);
        }

    }

    /**
     * 发红包
     * @param id
     */
    public static void sendRp(String id , double money , String type , int count) {

/**
 * 询问要发红包的用户id
 * 询问要发多少钱
 * 询问要发的红包类型
 * 询问发多少份红包
 * 在用户表中找到要发红包的用户，然后从该用户的balance中减去多少钱
 * 然后在t_redpackage_info中添加一条红包信息
 * 在t_child_redpackage_info中添加信息
 *
 */

        Connection conn = null;
        Statement statement = null;
        try {
            conn = RedpackageManager.getConn();
            statement = conn.createStatement();
            String sql = "update t_user_info set balance = balance - ? where user_id = ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setBigDecimal(1, new BigDecimal(money));
            ps.setString(2, id);
            int i = ps.executeUpdate();


            String sql1 = "insert into t_redpackage_info (user_id , rp_id , total_amt , rp_type , create_time) values (? , ? , ? , ? , ?)";
            PreparedStatement ps1 = conn.prepareStatement(sql1);
            ps1.setString(1, id);
            String rpid = System.currentTimeMillis()+"";
            ps1.setString(2, rpid);
            ps1.setBigDecimal(3, new BigDecimal(money));
            ps1.setString(4, type);
            ps1.setDate(5, new Date(System.currentTimeMillis()));
            int i1 = ps1.executeUpdate();


            String sql2 = "insert into t_child_redpackage_info (rp_id , amount , create_time) values (?,?,?)";
            for (int j = 0 ; j < count ; j++){
                PreparedStatement ps2 = conn.prepareStatement(sql2);
                ps2.setString(1, rpid);
                ps2.setBigDecimal(2, new BigDecimal(money/count));
                ps2.setDate(3, null);
                int i2 = ps2.executeUpdate();
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            RedpackageManager.close(conn,statement,null);
        }


    }

    /**
     * 抢红包
     * @param rpid
     */
    public static synchronized void robRp(String id, String rpid) {

        Connection conn = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            conn = RedpackageManager.getConn();
            statement = conn.createStatement();
            String sql = "SELECT id, amount FROM t_child_redpackage_info WHERE reciver_id = '还未领取'";
            resultSet = statement.executeQuery(sql);
            int id1 = 0;
            BigDecimal amount = null;
            while (resultSet.next()) {
                id1 = resultSet.getInt("id");
                amount = resultSet.getBigDecimal("amount");
            }
            if (id1 != 0) {
                String sql1 = "UPDATE t_child_redpackage_info SET reciver_id = ? , create_time = ? WHERE id = ?";
                PreparedStatement ps = conn.prepareStatement(sql1);
                ps.setString(1, id);
                ps.setDate(2, new Date(System.currentTimeMillis()));
                ps.setInt(3, id1);
                ps.executeUpdate();

                String sql2 = "UPDATE t_user_info SET balance = balance + ? WHERE user_id = ?";
                PreparedStatement ps1 = conn.prepareStatement(sql2);
                ps1.setBigDecimal(1, amount);
                ps1.setString(2, id);
                ps1.executeUpdate();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }RedpackageManager.close(conn, statement, resultSet);


    }

    public static void queryUserInfo(String id) {
        Connection conn = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            conn = RedpackageManager.getConn();
            statement = conn.createStatement();
            String sql = "SELECT * FROM t_user_info WHERE user_id =  ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, id);
            resultSet = ps.executeQuery();
            while (resultSet.next()) {
                System.out.println("查询结果："+"\n"+resultSet.getInt("id") +"\t"+resultSet.getString("user_id")
                        + "\t"+resultSet.getString("user_name") + "\t"+resultSet.getBigDecimal("balance"));
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }RedpackageManager.close(conn,statement,resultSet);

    }

    @Override
    public void run() {

           this.robRp(id1, id2);

    }
}
